using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using DevCangjie.utils.Settings;
using System.Linq;
using System.Threading.Tasks;

namespace DevCangjie.Pages.SettingsPage
{
    public sealed partial class SettingsPage : Page
    {
        // 缓存内容的字典，避免重复创建
        private Dictionary<string, UIElement> _contentCache = new();

        public List<string> AllFontFamiliesStr { get; set; } = Settings.AllFonts.Select(f => f.Name).ToList();

        private TextBox? pathTextBox;

        public SettingsPage()
        {
            this.InitializeComponent();

            // 默认选中第一个选项
            SettingsPageNavView.SelectedItem = SettingsPageNavView.MenuItems[0];
        }

        private async void Default_Click(object sender, RoutedEventArgs e)
        {
            // 加载默认设置文件
            Settings.Instance.Load(System.IO.Path.Combine(AppContext.BaseDirectory, "Resources", "DefaultSettings.json"));

            // 调用保存设置的方法
            Settings.Instance.Save();

            // 更新主窗口中所有打开的标签页和控制台的样式
            MainWindow.Current.RefreshUIStyles();

            // **清空内容缓存**
            _contentCache.Clear();

            // **重新加载当前选项的内容**
            if (SettingsPageNavView.SelectedItem is NavigationViewItem selectedItem)
            {
                string tag = selectedItem.Tag?.ToString();
                if (!string.IsNullOrEmpty(tag))
                {
                    UpdateContent(tag);
                }
            }

            // 提示用户恢复默认设置成功
            var dialog = new ContentDialog
            {
                Title = "设置",
                Content = "已恢复默认设置。",
                CloseButtonText = "确定",
                DefaultButton = ContentDialogButton.Close,
                XamlRoot = this.XamlRoot // Set the XamlRoot property
            };
            _ = dialog.ShowAsync();
        }

        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            // 调用保存设置的方法
            Settings.Instance.Save();

            Settings.Instance.Load(System.IO.Path.Combine(AppContext.BaseDirectory, "Settings.json"));

            // 更新主窗口中所有打开的标签页和控制台的样式
            MainWindow.Current.RefreshUIStyles();

            // 提示用户保存成功
            var dialog = new ContentDialog
            {
                Title = "设置",
                Content = "应用设置成功。JSON 文件位置：\n" + AppContext.BaseDirectory + "Settings.json",
                CloseButtonText = "确定",
                DefaultButton = ContentDialogButton.Close,
                XamlRoot = this.XamlRoot // Set the XamlRoot property
            };
            _ = dialog.ShowAsync();
        }

        private void NavigationView_SelectionChanged(object sender, NavigationViewSelectionChangedEventArgs e)
        {
            var selectedItem = e.SelectedItem as NavigationViewItem;

            if (selectedItem != null)
            {
                string tag = selectedItem.Tag?.ToString();

                if (!string.IsNullOrEmpty(tag))
                {
                    UpdateContent(tag);
                }
            }
        }

        public void SelectMenuItem(string tag)
        {
            // 遍历顶级菜单项
            foreach (var item in SettingsPageNavView.MenuItems)
            {
                if (item is NavigationViewItem navItem)
                {
                    if (navItem.Tag?.ToString() == tag)
                    {
                        SettingsPageNavView.SelectedItem = navItem;
                        return;
                    }

                    // 检查子菜单项
                    if (navItem.MenuItems != null)
                    {
                        foreach (var subItem in navItem.MenuItems)
                        {
                            if (subItem is NavigationViewItem subNavItem && subNavItem.Tag?.ToString() == tag)
                            {
                                SettingsPageNavView.SelectedItem = subNavItem;
                                return;
                            }
                        }
                    }
                }
            }
        }


        private void SettingsPageNavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
        {
            var clickedItem = args.InvokedItemContainer as NavigationViewItem;
            if (clickedItem != null)
            {
                var tag = clickedItem.Tag as string;
                if (tag == "OpenJsonFile")
                {
                    // 点击了设置按钮，执行打开文件的操作
                    try
                    {
                        string filePath = Path.Combine(AppContext.BaseDirectory, "Settings.json");

                        if (File.Exists(filePath))
                        {
                            // 使用默认程序打开文件
                            ProcessStartInfo psi = new ProcessStartInfo
                            {
                                FileName = filePath,
                                UseShellExecute = true // 必须设置为 true 才能使用默认关联的程序打开文件
                            };
                            Process.Start(psi);
                        }
                        else
                        {
                            // 文件不存在，提示用户
                            var dialog = new ContentDialog
                            {
                                Title = "错误",
                                Content = "未找到 Settings.json 文件。",
                                CloseButtonText = "确定",
                                XamlRoot = this.XamlRoot
                            };
                            _ = dialog.ShowAsync();
                        }
                    }
                    catch (Exception ex)
                    {
                        // 处理异常
                        var dialog = new ContentDialog
                        {
                            Title = "错误",
                            Content = $"无法打开文件：{ex.Message}",
                            CloseButtonText = "确定",
                            XamlRoot = this.XamlRoot
                        };
                        _ = dialog.ShowAsync();
                    }
                }
            }
        }

        private void UpdateContent(string tag)
        {
            // 如果缓存中已有对应的内容，直接使用
            if (_contentCache.TryGetValue(tag, out UIElement content))
            {
                ContentArea.Content = content;
            }
            else
            {
                // 创建新的内容并缓存
                content = CreateContent(tag);
                if (content != null)
                {
                    _contentCache[tag] = content;
                    ContentArea.Content = content;
                }
            }
        }

        private UIElement CreateContent(string tag)
        {
            // 创建一个 StackPanel，用于容纳动态添加的控件
            var panel = new StackPanel
            {
                Margin = new Thickness(20)
            };

            switch (tag)
            {
                case "StartOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "启动设置",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 20)
                    });
                    panel.Children.Add(new CheckBox
                    {
                        Content = "启动时打开上次打开的文件",
                        IsChecked = true,
                        Margin = new Thickness(0, 10, 0, 0)
                    });
                    CheckBox isWelcomePageShownCheckBox = new CheckBox
                    {
                        Content = "启动时打开欢迎界面",
                        IsChecked = Settings.Instance.IsWelcomePageShown,
                        Margin = new Thickness(0, 10, 0, 0)
                    };
                    isWelcomePageShownCheckBox.Checked += (s, e) =>
                    {
                        Settings.Instance.IsWelcomePageShown = true;
                    };
                    isWelcomePageShownCheckBox.Unchecked += (s, e) =>
                    {
                        Settings.Instance.IsWelcomePageShown = false;
                    };
                    panel.Children.Add(isWelcomePageShownCheckBox);
                    break;
                case "EditorOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "编辑器设置",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 20)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "请选择左侧的子选项进行设置。",
                        FontSize = 16
                    });
                    break;

                case "EditorFontOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "编辑器字体",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 20)
                    });

                    // 添加默认样式设置
                    var defaultFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 10, 0, 0)
                    };
                    defaultFontPanel.Children.Add(new TextBlock
                    {
                        Text = "默认样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    // 字体选择
                    var defaultFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleDefaultFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    defaultFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (defaultFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleDefaultFont = new FontFamily(selectedFont);
                        }
                    };
                    defaultFontPanel.Children.Add(defaultFontComboBox);
                    // 字体大小选择
                    var defaultFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = new List<string>
                        {
                            "5", "6", "7", "8", "9", "10", "11", "12", "14",
                            "16", "18", "20", "22", "24", "26", "28", "36",
                            "48", "72"
                        },
                        SelectedItem = Settings.Instance.StyleDefaultFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    defaultFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (defaultFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleDefaultFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(defaultFontSizeComboBox.Text))
                        {
                            if (int.TryParse(defaultFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleDefaultFontSize = fontSize;
                            }
                        }
                    };
                    defaultFontPanel.Children.Add(defaultFontSizeComboBox);
                    panel.Children.Add(defaultFontPanel);

                    // 添加行号样式设置
                    var lineNumberFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    lineNumberFontPanel.Children.Add(new TextBlock
                    {
                        Text = "行号样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    var lineNumberFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleLineNumberFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    lineNumberFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (lineNumberFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleLineNumberFont = new FontFamily(selectedFont);
                        }
                    };
                    lineNumberFontPanel.Children.Add(lineNumberFontComboBox);
                    var lineNumberFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = defaultFontSizeComboBox.ItemsSource,
                        SelectedItem = Settings.Instance.StyleLineNumberFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    lineNumberFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (lineNumberFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleLineNumberFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(lineNumberFontSizeComboBox.Text))
                        {
                            if (int.TryParse(lineNumberFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleLineNumberFontSize = fontSize;
                            }
                        }
                    };
                    lineNumberFontPanel.Children.Add(lineNumberFontSizeComboBox);
                    panel.Children.Add(lineNumberFontPanel);

                    // 添加括号样式设置
                    var braceLightFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    braceLightFontPanel.Children.Add(new TextBlock
                    {
                        Text = "括号样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    var braceLightFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleBraceLightFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    braceLightFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (braceLightFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleBraceLightFont = new FontFamily(selectedFont);
                        }
                    };
                    braceLightFontPanel.Children.Add(braceLightFontComboBox);
                    var braceLightFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = defaultFontSizeComboBox.ItemsSource,
                        SelectedItem = Settings.Instance.StyleBraceLightFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    braceLightFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (braceLightFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleBraceLightFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(braceLightFontSizeComboBox.Text))
                        {
                            if (int.TryParse(braceLightFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleBraceLightFontSize = fontSize;
                            }
                        }
                    };
                    braceLightFontPanel.Children.Add(braceLightFontSizeComboBox);
                    panel.Children.Add(braceLightFontPanel);

                    // 添加刷新错误（括号错误）样式设置
                    var braceBadFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    braceBadFontPanel.Children.Add(new TextBlock
                    {
                        Text = "刷新错误（括号错误）样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    var braceBadFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleBraceBadFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    braceBadFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (braceBadFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleBraceBadFont = new FontFamily(selectedFont);
                        }
                    };
                    braceBadFontPanel.Children.Add(braceBadFontComboBox);
                    var braceBadFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = defaultFontSizeComboBox.ItemsSource,
                        SelectedItem = Settings.Instance.StyleBraceBadFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    braceBadFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (braceBadFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleBraceBadFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(braceBadFontSizeComboBox.Text))
                        {
                            if (int.TryParse(braceBadFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleBraceBadFontSize = fontSize;
                            }
                        }
                    };
                    braceBadFontPanel.Children.Add(braceBadFontSizeComboBox);
                    panel.Children.Add(braceBadFontPanel);

                    // 添加控制字符样式设置
                    var controlCharFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    controlCharFontPanel.Children.Add(new TextBlock
                    {
                        Text = "控制字符样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    var controlCharFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleControlCharFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    controlCharFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (controlCharFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleControlCharFont = new FontFamily(selectedFont);
                        }
                    };
                    controlCharFontPanel.Children.Add(controlCharFontComboBox);
                    var controlCharFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = defaultFontSizeComboBox.ItemsSource,
                        SelectedItem = Settings.Instance.StyleControlCharFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    controlCharFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (controlCharFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleControlCharFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(controlCharFontSizeComboBox.Text))
                        {
                            if (int.TryParse(controlCharFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleControlCharFontSize = fontSize;
                            }
                        }
                    };
                    controlCharFontPanel.Children.Add(controlCharFontSizeComboBox);
                    panel.Children.Add(controlCharFontPanel);

                    // 添加缩进样式设置
                    var indentGuideFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    indentGuideFontPanel.Children.Add(new TextBlock
                    {
                        Text = "缩进样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    var indentGuideFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleIndentGuideFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    indentGuideFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (indentGuideFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleIndentGuideFont = new FontFamily(selectedFont);
                        }
                    };
                    indentGuideFontPanel.Children.Add(indentGuideFontComboBox);
                    var indentGuideFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = defaultFontSizeComboBox.ItemsSource,
                        SelectedItem = Settings.Instance.StyleIndentGuideFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    indentGuideFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (indentGuideFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleIndentGuideFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(indentGuideFontSizeComboBox.Text))
                        {
                            if (int.TryParse(indentGuideFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleIndentGuideFontSize = fontSize;
                            }
                        }
                    };
                    indentGuideFontPanel.Children.Add(indentGuideFontSizeComboBox);
                    panel.Children.Add(indentGuideFontPanel);

                    // 添加呼叫提示样式设置
                    var callTipFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    callTipFontPanel.Children.Add(new TextBlock
                    {
                        Text = "呼叫提示样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    var callTipFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleCallTipFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    callTipFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (callTipFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleCallTipFont = new FontFamily(selectedFont);
                        }
                    };
                    callTipFontPanel.Children.Add(callTipFontComboBox);
                    var callTipFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = defaultFontSizeComboBox.ItemsSource,
                        SelectedItem = Settings.Instance.StyleCallTipFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    callTipFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (callTipFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleCallTipFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(callTipFontSizeComboBox.Text))
                        {
                            if (int.TryParse(callTipFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleCallTipFontSize = fontSize;
                            }
                        }
                    };
                    callTipFontPanel.Children.Add(callTipFontSizeComboBox);
                    panel.Children.Add(callTipFontPanel);

                    // 添加折叠显示文本样式设置
                    var foldDisplayTextFontPanel = new StackPanel
                    {
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    foldDisplayTextFontPanel.Children.Add(new TextBlock
                    {
                        Text = "折叠显示文本样式",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    var foldDisplayTextFontComboBox = new ComboBox
                    {
                        Header = "选择字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.StyleFoldDisplayTextFont.Source,
                        Margin = new Thickness(0, 5, 0, 0)
                    };
                    foldDisplayTextFontComboBox.SelectionChanged += (s, e) =>
                    {
                        if (foldDisplayTextFontComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.StyleFoldDisplayTextFont = new FontFamily(selectedFont);
                        }
                    };
                    foldDisplayTextFontPanel.Children.Add(foldDisplayTextFontComboBox);
                    var foldDisplayTextFontSizeComboBox = new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = defaultFontSizeComboBox.ItemsSource,
                        SelectedItem = Settings.Instance.StyleFoldDisplayTextFontSize.ToString(),
                        Margin = new Thickness(0, 5, 0, 0),
                        IsEditable = true
                    };
                    foldDisplayTextFontSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (foldDisplayTextFontSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.StyleFoldDisplayTextFontSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(foldDisplayTextFontSizeComboBox.Text))
                        {
                            if (int.TryParse(foldDisplayTextFontSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.StyleFoldDisplayTextFontSize = fontSize;
                            }
                        }
                    };
                    foldDisplayTextFontPanel.Children.Add(foldDisplayTextFontSizeComboBox);
                    panel.Children.Add(foldDisplayTextFontPanel);

                    // 添加编辑器行间距设置
                    TextBox lineSpacingTextBox = new TextBox
                    {
                        Header = "编辑器行间距",
                        Text = Settings.Instance.TextLineSpacing.ToString(),
                        Margin = new Thickness(0, 20, 0, 0)
                    };
                    lineSpacingTextBox.TextChanged += (s, e) =>
                    {
                        if (int.TryParse(lineSpacingTextBox.Text, out int lineSpacing))
                        {
                            Settings.Instance.TextLineSpacing = lineSpacing;
                        }
                    };
                    panel.Children.Add(lineSpacingTextBox);
                    break;

                case "FormattingOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "格式化设置",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 20)
                    });
                    // 添加格式化设置控件
                    panel.Children.Add(new CheckBox
                    {
                        Content = "启用自动格式化",
                        IsChecked = false,
                        Margin = new Thickness(0, 10, 0, 0)
                    });

                    TextBox charSetTextBox = new TextBox
                    {
                        Header = "字符集",
                        Text = Settings.Instance.CharSet,
                        Margin = new Thickness(0, 10, 0, 0)
                    };
                    charSetTextBox.TextChanged += (s, e) =>
                    {
                        if (!string.IsNullOrEmpty(charSetTextBox.Text))
                        { 
                            Settings.Instance.CharSet = charSetTextBox.Text; 
                        }
                    };
                    panel.Children.Add(charSetTextBox);
                    break;

                case "CompilerOption":
                    // 保持原有内容
                    panel.Children.Add(new TextBlock
                    {
                        Text = "编译器",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });

                    panel.Children.Add(new TextBlock
                    {
                        Text = "环境变量设置",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 20)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "这里是编译器选项的设置。",
                        Margin = new Thickness(0, 0, 0, 10)
                    });

                    panel.Children.Add(new TextBlock
                    {
                        Text = "仓颉路径",
                        FontSize = 16,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    // 创建一个横向排列的 StackPanel，用于放置 TextBox 和 Button
                    var pathInputPanel = new StackPanel
                    {
                        Orientation = Orientation.Horizontal,
                        Margin = new Thickness(0, 10, 0, 0)
                    };
                    // 输入框，用户可以直接粘贴路径
                    pathTextBox = new TextBox
                    {
                        PlaceholderText = "请输入或选择环境变量路径",
                        Width = 300 // 可以根据需要调整宽度
                    };
                    // 浏览按钮，打开文件夹选择对话框
                    var browseButton = new Button
                    {
                        Content = "浏览",
                        Margin = new Thickness(10, 0, 0, 0)
                    };

                    // 将点击事件处理程序绑定到同步方法
                    browseButton.Click += BrowseButton_Click;

                    // 将 TextBox 和 Button 添加到横向 StackPanel
                    pathInputPanel.Children.Add(pathTextBox);
                    pathInputPanel.Children.Add(browseButton);

                    // 将横向 StackPanel 添加到面板
                    panel.Children.Add(pathInputPanel);

                    // 监听 TextBox 文本变化，以便手动输入时更新设置
                    pathTextBox.TextChanged += (s, e) =>
                    {
                        Settings.Instance.CangjiePath = pathTextBox.Text;
                    };

                    // 初始化时设置 TextBox 的文本
                    pathTextBox.Text = Settings.Instance.CangjiePath;

                    panel.Children.Add(new ComboBox
                    {
                        Header = "启用优化",
                        ItemsSource = new List<string>
                        {
                            "不启用", "O0 优化", "O1 优化", "O2 优化", "Os 优化", "Oz 优化"
                        },
                        SelectedIndex = 0,
                        Margin = new Thickness(0, 10, 0, 0)
                    });
                    break;

                case "ConsoleOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "控制台",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "请选择左侧的子选项进行设置。",
                        FontSize = 16
                    });
                    break;

                case "OutputOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "输出",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "这里是输出选项的设置。",
                        Margin = new Thickness(0, 0, 0, 10)
                    });

                    ComboBox outputFontFamilyComboBox = new ComboBox
                    {
                        Header = "控制台输出字体",
                        ItemsSource = AllFontFamiliesStr,
                        SelectedItem = Settings.Instance.ConsoleFont.Source,
                        Margin = new Thickness(0, 10, 0, 0),
                        IsEditable = true
                    };
                    outputFontFamilyComboBox.SelectionChanged += (s, e) =>
                    {
                        if (outputFontFamilyComboBox.SelectedItem is string selectedFont)
                        {
                            Settings.Instance.ConsoleFont = new FontFamily(selectedFont);
                        }
                        else if (!string.IsNullOrEmpty(outputFontFamilyComboBox.Text))
                        {
                            Settings.Instance.ConsoleFont = new FontFamily(outputFontFamilyComboBox.Text);
                        }
                    };
                    panel.Children.Add(outputFontFamilyComboBox);

                    ComboBox outputTextSizeComboBox = new ComboBox
                    {
                        Header = "控制台输出文本大小",
                        ItemsSource = new List<string>
                        {
                            "5", "6", "7", "8", "9", "10", "11", "12", "14",
                            "16", "18", "20", "22", "24", "26", "28", "36",
                            "48", "72"
                        },
                        SelectedItem = Settings.Instance.ConsoleSize.ToString(),
                        Margin = new Thickness(0, 10, 0, 0),
                        IsEditable = true
                    };
                    outputTextSizeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (outputTextSizeComboBox.SelectedItem is string selectedSize)
                        {
                            if (int.TryParse(selectedSize, out int fontSize))
                            {
                                Settings.Instance.ConsoleSize = fontSize;
                            }
                        }
                        else if (!string.IsNullOrEmpty(outputTextSizeComboBox.Text))
                        {
                            if (int.TryParse(outputTextSizeComboBox.Text, out int fontSize))
                            {
                                Settings.Instance.ConsoleSize = fontSize;
                            }
                        }
                    };
                    panel.Children.Add(outputTextSizeComboBox);
                    break;

                case "ErrorListOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "错误列表",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "这里是错误列表选项的设置。",
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    break;

                case "TerminalOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "终端",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "这里是终端选项的设置。",
                        Margin = new Thickness(0, 0, 0, 10)
                    });

                    CheckBox UseIntegratedTerminal = new CheckBox
                    {
                        Content = "使用集成终端",
                        IsChecked = Settings.Instance.RunProgramInIntegratedTerminal,
                        Margin = new Thickness(0, 10, 0, 0)
                    };
                    UseIntegratedTerminal.Checked += (s, e) =>
                    {
                        Settings.Instance.RunProgramInIntegratedTerminal = true;
                    };
                    UseIntegratedTerminal.Unchecked += (s, e) =>
                    {
                        Settings.Instance.RunProgramInIntegratedTerminal = false;
                    };
                    panel.Children.Add(UseIntegratedTerminal);
                    break;

                case "AppearanceOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "外观",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "这里是外观选项的设置。",
                        Margin = new Thickness(0, 0, 0, 10)
                    });

                    ComboBox themeComboBox = new ComboBox
                    {
                        Header = "主题",
                        ItemsSource = new List<string> { "浅色", "深色", "跟随系统" },
                        SelectedIndex = (int)Settings.Instance.CurrentTheme,
                        Margin = new Thickness(0, 10, 0, 0)
                    };
                    themeComboBox.SelectionChanged += (s, e) =>
                    {
                        if (themeComboBox.SelectedItem is string selectedTheme)
                        {
                            switch (selectedTheme)
                            {
                                case "浅色":
                                    Settings.Instance.UpdateTheme(Settings.Theme.Light);
                                    break;
                                case "深色":
                                    Settings.Instance.UpdateTheme(Settings.Theme.Dark);
                                    break;
                                case "跟随系统":
                                    Settings.Instance.UpdateTheme(Settings.Theme.SystemDefault);
                                    break;
                            }
                        }
                    };
                    panel.Children.Add(themeComboBox);

                    panel.Children.Add(new ComboBox
                    {
                        Header = "字体大小",
                        ItemsSource = new List<string>
                            {
                                "5", "6", "7", "8", "9", "10", "11", "12", "14",
                                "16", "18", "20", "22", "24", "26", "28", "36",
                                "48", "72"
                            },
                        SelectedIndex = 13,
                        Margin = new Thickness(0, 10, 0, 0),
                        IsEditable = true
                    });
                    break;

                case "OperationOption":
                    // 保持原有内容
                    panel.Children.Add(new TextBlock
                    {
                        Text = "操作",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    panel.Children.Add(new TextBlock
                    {
                        Text = "这里是操作选项的设置。",
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    panel.Children.Add(new Slider
                    {
                        Header = "灵敏度",
                        Minimum = 1,
                        Maximum = 10,
                        Value = 5,
                        Margin = new Thickness(0, 10, 0, 0)
                    });
                    break;

                case "AboutOption":
                    panel.Children.Add(new TextBlock
                    {
                        Text = "关于",
                        FontSize = 24,
                        Margin = new Thickness(0, 0, 0, 10)
                    });
                    break;
            }

            return panel;
        }

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            // 启动异步任务，但不等待其完成
            _ = BrowseButton_ClickAsync();
        }

        private async Task BrowseButton_ClickAsync()
        {
            try
            {
                var folderPicker = new Windows.Storage.Pickers.FolderPicker
                {
                    SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop
                };
                folderPicker.FileTypeFilter.Add("*");

                var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.m_window);
                WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hwnd);

                Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
                if (folder != null)
                {
                    if (pathTextBox != null)
                    {
                        pathTextBox.Text = folder.Path;
                        Settings.Instance.CangjiePath = folder.Path;
                    }
                    else
                    {
                        // Handle the null case, possibly logging an error or showing a message to the user
                        var dialog = new ContentDialog
                        {
                            Title = "错误",
                            Content = "路径文本框未初始化。",
                            CloseButtonText = "确定",
                            DefaultButton = ContentDialogButton.Close,
                            XamlRoot = this.XamlRoot
                        };
                        await dialog.ShowAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常，避免未捕获的异常导致程序崩溃
                var dialog = new ContentDialog
                {
                    Title = "错误",
                    Content = $"无法选择文件夹：{ex.Message}",
                    CloseButtonText = "确定",
                    DefaultButton = ContentDialogButton.Close,
                    XamlRoot = this.XamlRoot
                };
                await dialog.ShowAsync();
            }
        }
    }
}